<template>
  <div class="mainpg">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <div class="mainor_form">
          <div class="mainor_te"></div>
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="70px"
          >
            <el-form-item label="线路名称" prop="line">
              <el-input
                v-model.trim="form.line"
                placeholder="线路名称"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item class>
              <el-button
                class="reset marginLeft10"
                type="primary"
                @click="$refs['userListFrom'].resetFields()"
                >重置</el-button
              >
              <el-button
                type="primary"
                @click="getArticleList"
                :loading="listLoading"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="main_num boxdq">
          <div class="main_num_l box">
            <p>1.权重设置是智能推荐的重要依据</p>
            <p>2.每条线路设置区域权重和车辆权重不设上限</p>
            <p>3.区域和车辆可在其它线路重复设置，但排位不能重复</p>
            <p>4.以添加次序计算排位，排位越靠前权重越高</p>
          </div>
          <div class="mainsu_te" style="position: relative"></div>
        </div>
        <div class="main_table" style="min-height: 640px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list"
            element-loading-text="加载中"
            fit
            highlight-current-row
          >
            <el-table-column
              label="线路名称"
              prop="title"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="区域" prop="" class-name="main_hei">
              <template slot-scope="scope">
                <div class="row_box">
                  {{ scope.row.regionContent }}
                </div>
              </template></el-table-column
            >
            <el-table-column
              label="车辆"
              prop="carContent"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <div class="row_box">
                  {{ scope.row.carContent }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="维护权重"
              prop=""
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <template>
                  <el-link
                    type="success"
                    @click="formula_meth(scope.row, scope.$index, 1)"
                    >区域</el-link
                  >
                </template>
                <template>
                  <el-link
                    type="success"
                    @click="formula_meth(scope.row, scope.$index, 2)"
                    >车辆</el-link
                  >
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <el-pagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 区域 -->
    <el-dialog
      title="区域权重"
      :visible.sync="regionVisible"
      class="main_dialog dialog700"
    >
      <div>
        <el-transfer
          v-model="region_select_list"
          :data="region_list"
          :titles="['待添加', '已添加']"
          :button-texts="['移除', '添加']"
          ref="transfer"
          id="transfer"
          target-order="push"
        >
          <span
            slot-scope="{ option }"
            :draggable="!option.disabled"
            @dragstart="drag($event, option)"
          >
            {{ option.label }}</span
          >
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="regionVisible = false">取 消</el-button>
        <el-button type="primary" @click="save_region">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 车辆 -->
    <el-dialog
      title="车辆权重"
      :visible.sync="carVisible"
      class="main_dialog dialog700"
    >
      <div>
        <el-transfer
          v-model="car_select_list"
          :data="car_list"
          :titles="['待添加', '已添加']"
          :button-texts="['移除', '添加']"
          ref="transfer_car"
          id="transfer_car"
          target-order="push"
        >
          <span
            slot-scope="{ option }"
            :draggable="!option.disabled"
            @dragstart="drag($event, option)"
          >
            {{ option.label }}</span
          >
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="carVisible = false">取 消</el-button>
        <el-button type="primary" @click="save_car">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  lineWeight_index,
  lineWeight_bind,
  lineWeight_delete,
  lineWeight_getCarList,
  lineWeight_getRegionList,
} from "@/api/distribution/distributionLinePlan";
import Sortable from "sortablejs";
import rules from "@/rules/distribution/distributionLine";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime } from "@/utils/index";

export default {
  components: {},
  data() {
    return {
      parseTime,
      // 增加和编辑
      info: {
        title: "",
      },
      type: 0,
      id: 0,
      addedFormVisible: false,
      // 搜索
      form: {
        line: "",
      },
      // 验证
      rules,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      car_list: {},
      list: [],
      region: {},
      listLoading: false,
      // 分组

      line_id: "",
      regionVisible: false,
      region_list_origin: [],
      region_select_list: [],
      region_list: [],

      carVisible: false,
      car_select_list: [],
      car_list_origin: [],
      car_list: [],
      draggingKey: null,
    };
  },
  methods: {
    drag(ev, option) {
      this.draggingKey = option.key;
    },
    // 弹出层
    formula_meth(row, index, type) {
      let id = row.id;
      this.line_id = id;
      switch (type) {
        case 1:
          this.lineWeight_getRegionList(id)
            .then(() => {
              this.regionVisible = true;
              this.$nextTick(() => {
                this.DRAG();
              });
            })
            .catch(() => {
              this.$message.error("请求数失败");
            });
          break;
        case 2:
          this.lineWeight_getCarList(id)
            .then(() => {
              this.carVisible = true;
              this.$nextTick(() => {
                this.DRAG1();
              });
            })
            .catch(() => {
              this.$message.error("请求数据失败");
            });
          break;
      }
    },
    save_region() {
      let form = {
        line_id: this.line_id,
        list: JSON.stringify(this.region_select_list),
        type: 1, //1 区域   2车辆
      };
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        form,
        apiUrl().name
      );
      lineWeight_bind(data).then((res) => {
        if (res.errcode == 0) {
          this.regionVisible = false;
          this.lineWeight_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    save_car() {
      let form = {
        line_id: this.line_id,
        list: JSON.stringify(this.car_select_list),
        type: 2, //1 区域   2车辆
      };
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        form,
        apiUrl().name
      );
      lineWeight_bind(data).then((res) => {
        if (res.errcode == 0) {
          this.carVisible = false;
          this.lineWeight_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    handleGroup() {},
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.lineWeight_index();
    },

    // 分页{}
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.lineWeight_index();
    },
    changePage(page) {
      this.current.page = page;
      this.lineWeight_index();
    },
    // 列表
    lineWeight_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.form,
        this.current
      );
      lineWeight_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          res.data.list.map((e) => {
            let regionarr = [];
            let carcrr = [];
            if (e.region) {
              e.region.map((r) => {
                regionarr.push(r.title);
              });
            }
            if (e.car) {
              e.car.map((c) => {
                carcrr.push(c.plate_number);
              });
            }
            e.regionContent = regionarr.join("-->");
            e.carContent = carcrr.join("-->");
          });
          this.car_list = res.data.car;
          this.list = res.data.list;
          this.region = res.data.region;
          this.totalCount = res.data.count;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 获取车辆的选择列表
    lineWeight_getCarList(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      return new Promise((resolve, reject) => {
        lineWeight_getCarList(data).then((res) => {
          if (res.errcode == 0) {
            let arr = [];
            for (let item in res.data.list) {
              let obj = {
                key: item,
                label: res.data.list[item],
              };
              arr.push(obj);
            }
            let select = [];
            res.data.list_ed.map((e) => {
              select.push(String(e.id));
            });

            this.car_select_list = select;
            this.car_list = arr;
            resolve();
          } else {
            reject();
          }
        });
      });
    },
    // 获取区域的选择列表
    lineWeight_getRegionList(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      return new Promise((resolve, reject) => {
        lineWeight_getRegionList(data).then((res) => {
          if (res.errcode == 0) {
            let arr = [];
            for (let item in res.data.list) {
              let obj = {
                key: item,
                label: res.data.list[item],
              };
              arr.push(obj);
            }

            let select = [];
            res.data.list_ed.map((e) => {
              select.push(String(e.id));
            });
            this.region_select_list = select;
            this.region_list = arr;

            resolve();
          } else {
            reject();
          }
        });
      });
    },
    DRAG() {
      const transfer = this.$refs.transfer.$el;
      const leftPanel = transfer
        .getElementsByClassName("el-transfer-panel")[0]
        .getElementsByClassName("el-transfer-panel__body")[0];
      const rightPanel = transfer
        .getElementsByClassName("el-transfer-panel")[1]
        .getElementsByClassName("el-transfer-panel__body")[0];
      const rightEl = rightPanel.getElementsByClassName(
        "el-transfer-panel__list"
      )[0];
      Sortable.create(rightEl, {
        onEnd: (evt) => {
          const { oldIndex, newIndex } = evt;
          const temp = this.region_select_list[oldIndex];
          if (!temp || temp === "undefined") {
            return;
          } // 解决右边最后一项从右边拖左边，有undefined的问题
          this.$set(
            this.region_select_list,
            oldIndex,
            this.region_select_list[newIndex]
          );
          this.$set(this.region_select_list, newIndex, temp);
        },
      });
      const leftEl = leftPanel.getElementsByClassName(
        "el-transfer-panel__list"
      )[0];
      Sortable.create(leftEl, {
        onEnd: (evt) => {
          const { oldIndex, newIndex } = evt;
          const temp = this.region_list[oldIndex];
          e;
          if (!temp || temp === "undefined") {
            return;
          } // 解决右边最后一项从右边拖左边，有undefined的问题
          this.$set(this.region_list, oldIndex, this.region_list[newIndex]);
          this.$set(this.region_list, newIndex, temp);
        },
      });
      leftPanel.ondragover = (ev) => {
        ev.preventDefault();
      };
      leftPanel.ondrop = (ev) => {
        ev.preventDefault();
        const index = this.region_select_list.indexOf(this.draggingKey);
        if (index !== -1) {
          this.region_select_list.splice(index, 1);
        }
      };
      rightPanel.ondragover = (ev) => {
        ev.preventDefault();
      };
      rightPanel.ondrop = (ev) => {
        ev.preventDefault();
        if (this.region_select_list.indexOf(this.draggingKey) === -1) {
          this.region_select_list.push(this.draggingKey);
        }
      };
    },
    DRAG1() {
      const transfer = this.$refs.transfer_car.$el;
      const leftPanel = transfer
        .getElementsByClassName("el-transfer-panel")[0]
        .getElementsByClassName("el-transfer-panel__body")[0];
      const rightPanel = transfer
        .getElementsByClassName("el-transfer-panel")[1]
        .getElementsByClassName("el-transfer-panel__body")[0];
      const rightEl = rightPanel.getElementsByClassName(
        "el-transfer-panel__list"
      )[0];
      Sortable.create(rightEl, {
        onEnd: (evt) => {
          const { oldIndex, newIndex } = evt;
          const temp = this.car_select_list[oldIndex];
          if (!temp || temp === "undefined") {
            return;
          } // 解决右边最后一项从右边拖左边，有undefined的问题
          this.$set(
            this.car_select_list,
            oldIndex,
            this.car_select_list[newIndex]
          );
          this.$set(this.car_select_list, newIndex, temp);
        },
      });
      const leftEl = leftPanel.getElementsByClassName(
        "el-transfer-panel__list"
      )[0];
      Sortable.create(leftEl, {
        onEnd: (evt) => {
          const { oldIndex, newIndex } = evt;
          const temp = this.car_list[oldIndex];
          e;
          if (!temp || temp === "undefined") {
            return;
          } // 解决右边最后一项从右边拖左边，有undefined的问题
          this.$set(this.car_list, oldIndex, this.car_list[newIndex]);
          this.$set(this.car_list, newIndex, temp);
        },
      });
      leftPanel.ondragover = (ev) => {
        ev.preventDefault();
      };
      leftPanel.ondrop = (ev) => {
        ev.preventDefault();
        const index = this.car_select_list.indexOf(this.draggingKey);
        if (index !== -1) {
          this.car_select_list.splice(index, 1);
        }
      };
      rightPanel.ondragover = (ev) => {
        ev.preventDefault();
      };
      rightPanel.ondrop = (ev) => {
        ev.preventDefault();
        if (this.region_select_list.indexOf(this.draggingKey) === -1) {
          this.region_select_list.push(this.draggingKey);
        }
      };
    },
  },
  created() {
    // 列表
    this.lineWeight_index();
  },
  mounted() {},
  updated() {},
};
</script>
<style lang="scss" scoped>
.mainor_form form {
  width: calc(100% - 120px);
}
.main_num_l p {
  margin-right: 25px;
  color: #e47c02;
}
// 标签
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
/deep/.el-table__expanded-cell {
  padding: 12px 20px !important;
}
.row_box {
  width: 100%;
}
</style>
